import breaDcrumb from '@/components/breadcrumb';
import {
  getListByTypeId
} from '@/api/common.js';
import {
  getFirmDetection,
  getNormByDetection
} from '@/api/basicConfig/CPYquality.js';
import {
  saveStationTest,
  getStationTest,
  getStationNormByDetection,
  // saveNormByDetection
} from '@/api/basicConfig/Sitequality.js';
import {
  getContracts,
  getContractList
} from "@/api/GHnumber/share.js";
import { getDicType } from "@/api/common.js";
import { getUserInfo } from "@/utils/auth.js";
import { getcompany, getUserAutList, get_simple_organization, getStationByCompanyId } from "@/api/common.js";
import LabelLife from '../components/sitelabelLife.vue';
let oldList = []
export default {
  components: {
    breaDcrumb,
    LabelLife
  },
  data() {
    return {
      UserInfo: '',
      contractTypelist: [{
        value: '验收标准',
        id: 0
      },
      {
        value: '检测频率设置',
        id: 1
      },
      {
        value: '标号寿命预警',
        id: 2
      }],
      currenindex: 1,
      companyId: '',
      companylist: [],
      showsiteId: '',
      siteId: '',
      siteIdList: [],
      // 左侧导航
      leftList: [{
        text: '原物料',
        value: 1
      }, {
        text: '强度等级',
        value: 2
      },
      {
        text: '规范性能等级',
        value: 3
      },

      ],
      leftIndex: 1,
      showleftIndex: 1,
      // 左侧数据
      leftitemList: [],
      leftitemId: '',
      showleftitemId: '',
      //模块一
      rightIndex: '',
      showrightIndex: '',
      categoryList: [{
        name: '请优先选择对应的原物料或者强度等级'
      }],
      tablenav: [],
      rightitemList: [],
      showrightitemList: [],
      Dialog: false,
      newtablenav: [],
      newrightitemList: [],
      tableLoading: false,
      //模块二
      //合同
      contactId: '',
      contactIdist: [],
      //类别
      leftId: '',
      leftIdList: [],
      // 频率
      rightId: [],
      rightIdList: [{
        itemName: "车",
        id: "1",
        content: ''
      },
      {
        itemName: "吨",
        id: "2",
        content: ''
      },
      {
        itemName: "方",
        id: "3",
        content: ''
      },
      {
        itemName: "小时",
        id: "4",
        content: ''
      }],
      /*存数据*/
      itema: '',
      itemb: '',
      itemc: '',
      /**判断是否是交工数据*/
      signData: false,
      orderNum: '',
      orderStatus: 0,
      production: '',
      productionStatus: 0,
      IntervalState: false,
      stateList: [
        { belowValue: '', topValue: '', frequencyId: 5, content: '' },
        { belowValue: '', topValue: '', frequencyId: 5, content: '' }
      ],
      /**保存是否存在修改*/
      loading: false,
      showcontactId: '',
      showleftId: ''
    };
  },
  async created() {
    this.UserInfo = await getUserInfo();
    if (this.UserInfo.adminStatus == 1) {
      /**通过typeId为公司类型id查询所有公司 */
      getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
        this.companylist = res.data;
        this.companyId = res.data[0].id
        getStationByCompanyId({ id: this.companyId }).then((res) => {
          this.siteIdList = res.data.map(res => ({ name: res.stationName, id: res.id }));
          if (this.siteIdList.length > 0) {
            this.siteId = this.siteIdList[0].id
            this.showsiteId = this.siteIdList[0].id
          } else {
            this.siteId = ''
            this.showsiteId = ''
          }
        });
      });
    } else {
      this.siteIdList = await getUserAutList(true)
      this.siteId = this.siteIdList[0].id
      this.showsiteId = this.siteIdList[0].id
      await this.get_simple_organizationFun(this.siteId)
    }
  },
  watch: {
    /*验收标准，检测频率切换*/
    currenindex() {
      this.initright()
    },
    /*更改站点*/
    siteId() {
      if (this.currenindex == 1) {
        this.clearAll()
      } else {
        this.getTable()
      }
    },
    /*更改公司*/
    async companyId() {
      this.showleftitemId = ''
      this.leftitemId = ''
      this.rightIndex = ''
      this.showrightIndex = ''
      this.categoryList = [{
        name: '暂未绑定检测类别'
      }]
      if (this.currenindex == 0) {
        await this.gettightList()
      }
    },
    /*更改原物料或者强度等级*/
    leftitemId() {
      if (this.currenindex == 0) {
        /**验收标准*/
        this.getNewData()
      } else {
        /**检测频率清空*/
        this.clearAll()
      }

    },
    /*** 原物料或者强度切换后*/
    leftIndex: {
      handler() {
        this.showleftitemId = ''
        this.leftitemId = ''
        if (this.currenindex == 0) {
          /**验收标准清空*/
          this.initright()
        } else {
          /**检测频率清空*/
          this.clearAll()
        }
        switch (this.leftIndex) {
          case 1: {
            getDicType({
              code: "MATname"
            }).then((res) => {
              this.leftitemList = res.data.items.map((res) => {
                let obj = {
                  id: res.id,
                  name: res.itemName,
                };
                return obj;
              });
            });
            return;
          }
          case 2: {
            getListByTypeId({
              typeId: 1
            }).then(res => {
              this.leftitemList = res.data;
            });
            return;
          }
          case 3: {
            getListByTypeId({
              typeId: 2
            }).then(res => {
              this.leftitemList = res.data.filter(res => (res.name[0] == 'p' || res.name[0] == 'P'))
            });
            return;
          }
        }
      },
      deep: false, //是否深度监听，true为是，默认为false
      immediate: true //immediate表示在watch中首次绑定的时候，是否执
    },
    /*右侧检测类别*/
    rightIndex() {
      this.getTable()
    },
    /**合同和验收类捏更改后获取绑定的频率*/
    dateRange() {
      if (this.leftIndex == 3 && this.contactId) {
        this.getStation()
        return
      }
      if (this.contactId && this.leftId && this.leftIndex !== 3) {
        this.getStation()
        return
      }
    }
  },
  computed: {
    dateRange() {
      const contactId = this.contactId
      const leftId = this.leftId
      return { contactId, leftId }
    },
  },
  methods: {
    /**通过站点查询公司 */
    async get_simple_organizationFun(id) {
      await get_simple_organization({ id: id }).then((res) => {
        this.companyId = res.data?.id || ''
        this.company = res.data?.name || ''
      });
    },
    /*根据公司获取站点*/
    setstationIdlist() {
      getStationByCompanyId({ id: this.companyId }).then((res) => {
        this.siteIdList = res.data.map(res => ({ name: res.stationName, id: res.id }));
        if (this.siteIdList.length > 0) {
          this.siteId = this.siteIdList[0].id
          this.showsiteId = this.siteIdList[0].id
        } else {
          this.siteId = ''
          this.showsiteId = ''
        }
      });
    },
    /**验收标准*/
    /**获取检测类别*/
    gettightList() {
      let _this = this
      let data = new Object();
      data.type = _this.leftIndex;
      data.companyId = _this.companyId;
      if (_this.leftIndex == 1) {
        data.rawId = _this.leftitemId;
      } else {
        data.strengthGradeId = _this.leftitemId;
      }
      getFirmDetection(data).then(res => {
        if (res.data.length == 0) {
          _this.rightIndex = ''
          _this.showrightIndex = ''
          _this.categoryList = [{
            name: '暂未绑定检测类别'
          }]
        } else {
          _this.categoryList = res.data;
          _this.rightIndex = res.data[0].id
          _this.showrightIndex = res.data[0].id
        }
      });
    },
    /*获取表数据*/
    getTable() {
      if (this.companyId == '' || this.siteId == '' || this.leftitemId == '') {
        return
      }
      this.tableLoading = true
      let data = new Object();
      data.type = this.leftIndex;
      data.companyId = this.companyId;
      data.stationId = this.siteId;
      data.id = this.rightIndex
      if (this.leftIndex == 1) {
        data.rawId = this.leftitemId;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      getStationNormByDetection(data).then(res => {
        this.tableLoading = false
        this.tablenav = res.data?.claim || []
        this.rightitemList = this.copy(res.data?.list || [])
        this.showrightitemList = this.copy(res.data?.list || [])
        this.tablenav.unshift({
          name: "检测类别"
        })

      })
    },
    /**站点获取验收*/
    async getNewData() {
      if (this.leftitemId == '') {
        return;
      }
      this.gettightList()
    },
    /*获取公司标准*/
    getnewtable() {
      if (this.companyId == '' || this.siteId == '' || this.leftitemId == '') {
        this.$message({
          showClose: true,
          message: '警告哦，请选择对应的数据后再获取公司标准',
          type: 'warning'
        });
        return
      }
      let data = new Object();
      data.type = this.leftIndex;
      data.companyId = this.companyId;
      data.id = this.rightIndex
      data.checkStatus = 2
      if (this.leftIndex == 1) {
        data.rawId = this.leftitemId;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      getNormByDetection(data).then(res => {
        this.newtablenav = res.data.claim
        this.newrightitemList = this.copy(res.data.list)
        this.newtablenav.unshift({
          name: "检测类别"
        })
        let name = this.categoryList.find(res => (res.id == this.rightIndex))?.name
        if (name == '交工数据标准') {
          this.signData = true
        } else {
          this.signData = false
        }
        this.Dialog = true
      })
    },
    /*拷贝*/
    copy(list) {
      let str = JSON.stringify(list)
      return JSON.parse(str)
    },
    judge(str) {
      let re = new RegExp(/^[1-9][0-9]*,[1-9][0-9]*$/);
      return !re.test(str)
    },
    addnbd() {
      let _this = this
      /*构造数据对象*/
      let station = _this.siteIdList.find(res => (res.id == _this.siteId)).name
      function setdata(parameterSettingId, content) {
        this.type = _this.leftIndex;
        this.companyId = _this.companyId;
        this.stationId = _this.siteId;
        this.parameterSettingId = parameterSettingId;
        this.content = content;
        if (_this.leftIndex == 1) {
          this.rawId = _this.leftitemId;
        } else {
          this.strengthGradeId = _this.leftitemId;
        }
      }
      let arr = []
      try {
        this.rightitemList.forEach(res => {
          for (let key in res) {
            if (key !== '0') {
              arr.push(new setdata(res[key]?.id, res[key]?.name, res[key]?.lowerLimitValue, res[key]?.upperLimitValue))
              if (res[key]?.type == 3 && res[key]?.symbol.length !== 1) {
                if (this.judge(res[key]?.name)) {
                  throw Error();
                }
              }
            }
          }
        })
      } catch (e) {
        console.log(e)
        this.$message({
          message: '警告哦，数字为区间是请输入正确格式，如：10,20',
          type: 'warning'
        });
        return;
      }
      this.rightitemList.forEach(res => {
        console.log(res)
        for (let key in res) {
          if (key !== '0') {
            arr.push(new setdata(res[key]?.id, res[key]?.name))
          }
        }
      })
      for (let key in arr) {
        if (arr[key]?.content == '') {
          this.$message({
            message: '请选择要操作的数据项',
            type: 'warning'
          });
          return;
        }
      }
      let name = this.leftitemList.find(res => (res.id == this.showleftitemId)).name
      let nameType = this.categoryList.find(res => (res.id == this.rightIndex)).name
      this.$router.push({ name: "sign_Sitequality", query: { tablenav: JSON.stringify(this.tablenav), rightitemList: JSON.stringify(this.rightitemList), arr: JSON.stringify(arr), company: this.company, station: station, name: name, nameType: nameType, type: 1 } });
      console.log(this.tablenav)
      console.log(arr)
      console.log(this.rightitemList)
      console.log(this.company)
      console.log(station)
      console.log(this.leftitemList.find(res => (res.id == this.showleftitemId)).name)
      // saveNormByDetection(arr).then(() => {
      //   _this.getTable()
      // })
    },
    initright() {
      this.rightIndex = ''
      this.showrightIndex = ''
      this.categoryList = [{
        name: '请优先选择对应的原物料或者强度等级'
      }]
      this.tablenav = []
      this.rightitemList = []
      this.showrightitemList = []
      this.contactIdist = []
      this.leftIdList = []
      this.showleftitemId = ''
      this.leftitemId = ''
      this.contactId = ''
      this.leftId = ''
      this.rightId = []
      this.itema = ''
      this.itemb = ''
      this.itemc = []
    },
    /*验收频率切换*/
    choose(num) {
      this.currenindex = num
      if (this.currenindex == 1) {
        this.leftList.push({
          text: '规范性能等级',
          value: 3
        })
      } else {
        this.leftList.length = 2
      }

    },
    change(hid, show, value) {
      let _this = this;
      if (_this.currenindex == 1) {
        if (_this.loading) {
          _this.$confirm('请保存更改数据,否则数据将会丢失?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            cancelButtonClass: 'bottom_all_two',
            confirmButtonClass: 'bottom_all',
            type: 'warning'
          }).then(() => {
            _this[show] = _this[hid]
            _this.saveStation();

          }).catch(() => {
            _this[show] = value;
            _this[hid] = value;
            _this.loading = false;
          });
          return;
        }
        _this[show] = value;
        _this[hid] = value;
      } else {
        if (JSON.stringify(_this.showrightitemList) !== JSON.stringify(_this.rightitemList)) {
          _this.$confirm('请保存更改数据,否则数据将会丢失?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            cancelButtonClass: 'bottom_all_two',
            confirmButtonClass: 'bottom_all',
            type: 'warning'
          })
            .then(() => {
              _this[show] = _this[hid]
              _this.addnbd();

            })
            .catch(() => {
              _this[show] = value;
              _this[hid] = value;
            });
          return;
        }
        _this[show] = value;
        _this[hid] = value;
      }

    },

    /**检测频率设置*/
    /**获取合同并清除合同的选中*/
    async getContract() {
      if (this.siteId && this.leftitemId) {
        if (this.leftIndex === 1) {
          let data = {
            id: this.leftitemId,
            stations: this.siteId,
          };
          await getContracts(data).then((res) => {
            const newData = res.data.map((item => ({ ...item, name: `${item.contractNo}-${item.supplier}` })))
            this.contactIdist = newData;
            this.contactIdist.splice(0, 0, { name: '通用设置', contractId: '0' })
          });
        } else {
          const params = {
            stationId: this.siteId,
            materialsId: this.leftitemId,
            materialsType: this.leftIndex === 2 ? '1' : '2',
          };
          await getContractList(params).then((res) => {
            const newData = res.data.map((item => ({ ...item, name: `${item.ccContractNo}-${item.enginnerrName}` })))
            this.contactIdist = newData;
            this.contactIdist.splice(0, 0, { name: '通用设置', contractId: '0' })
          });
        }
      } else {
        this.contactIdist = []
        this.contactIdist.splice(0, 0, { name: '通用设置', contractId: '0' })
      }
      this.contactId = ''
      this.showcontactId = ''
    },
    /**获取检测类别,并清除选中*/
    async gettightList2() {
      let data = new Object();
      data.type = this.leftIndex;
      data.all = 1
      data.companyId = this.companyId;
      if (this.leftIndex == 1) {
        data.rawId = this.leftitemId;
      } else {
        data.strengthGradeId = this.leftitemId;
      }
      await getFirmDetection(data).then(res => {
        console.log(123);
        if (res.data.length == 0 || this.contactIdist.length == 0) {
          this.leftIdList = []
          this.leftId = ''
          this.showleftId = ''
        } else {
          this.leftIdList = res.data;
          this.leftId = ''
          this.showleftId = ''
        }
      });
    },
    /**清空所有数据*/
    async clearAll() {
      let _this = this
      await _this.getContract()
      await _this.gettightList2()
      oldList = []
      _this.rightId = []
      _this.IntervalState = false
      _this.stateList = _this.$options.data().stateList
      _this.orderStatus = 0
      _this.orderNum = null
      _this.productionStatus = 0
      _this.production = null

    },
    async clearRight() {
      let _this = this
      oldList = []
      _this.rightId = []
      _this.IntervalState = false
      _this.stateList = _this.$options.data().stateList
      _this.orderStatus = 0
      _this.orderNum = null
      _this.productionStatus = 0
      _this.production = null
    },
    /*获取绑定频率,先获取站点的参数，公司没有则恢复默认*/
    async getStation() {
      let _this = this;
      _this.$data.rightIdList = _this.$options.data().rightIdList
      if (_this.siteId == '' || _this.companyId == '' || _this.leftitemId == '') {
        return
      }
      let data = new Object();
      data.materialsType = _this.leftIndex;
      data.companyId = _this.companyId;
      data.materialsId = _this.leftitemId;
      data.stationId = _this.siteId
      data.contractId = _this.contactId
      data.qualityDetectionId = _this.leftId
      getStationTest(data).then(res => {
        if (res.data.length > 0) {
          oldList = JSON.parse(JSON.stringify(res.data))
          /**回显每...*/
          _this.rightId = res.data.filter(res => (res.frequencyId * 1 !== 5)).map(item => (item.frequencyId))
          res.data.forEach((v) => {
            _this.rightIdList.forEach((v2) => {
              if (v2.id == v.frequencyId) {
                v2.content = v.content
              }
            })
          })
          /**回显检验前置条件*/
          _this.orderStatus = res.data[0].checkOrderNum
          _this.orderNum = res.data[0].orderNum
          _this.productionStatus = res.data[0].checkProduction
          _this.production = res.data[0].production
          /**回显累计生产量*/
          let content = res.data.find(res => (res.frequencyId == 5))
          _this.IntervalState = Boolean(content)
          if (!content?.content) {
            _this.stateList = _this.$options.data().stateList
            return
          }
          _this.stateList = JSON.parse(content?.content).map(res => (
            { belowValue: '', topValue: res.num, frequencyId: 5, content: res.value }
          ))
        } else {
          _this.clearRight()
        }
      })
    },
    changeLoading() {
      if (this.leftIndex == 3 && this.leftitemId && this.contactId) {
        this.loading = true
      }
      if (this.leftitemId && this.leftId && this.leftIndex !== 3 && this.contactId) {
        this.loading = true
      }
    },
    /*累计生产量的增删*/
    addItem() {
      this.stateList.push(
        { belowValue: '', topValue: '', frequencyId: 5, content: '' }
      )
    },
    delItem(item, index) {
      if (item.id) {
        item.status = 0
        return
      }
      this.stateList.splice(index, 1)
    },
    /**保存*/
    async saveStation() {
      let _this = this
      function setdata(content, frequencyId, frequency, id) {
        this.id = id
        this.companyId = _this.companyId
        this.content = content
        this.contractId = _this.contactId
        this.stationId = _this.siteId
        this.frequency = frequency
        this.frequencyId = frequencyId
        this.materialsId = _this.leftitemId
        this.materialsName = _this.leftitemList.find(res => (res.id == _this.leftitemId))?.name
        this.materialsType = _this.leftIndex
        this.orderNum = _this.orderNum
        this.production = _this.production
        this.qualityDetection = _this.leftIdList.find(res => (res.id == _this.leftId))?.name
        this.qualityDetectionId = _this.leftId
        this.checkOrderNum = _this.orderStatus
        this.checkProduction = _this.productionStatus
      }
      let arr = []
      _this.rightId.forEach((v) => {
        arr.push(
          new setdata(
            _this.rightIdList.find(res => (res.id == v))?.content,
            v,
            _this.rightIdList.find(res => (res.id == v))?.itemName,
            oldList.find(res => (res.frequencyId == v))?.id
          ),
        )
      })
      if (_this.IntervalState) {
        let content = _this.stateList.map(res => ({ num: Number(res.topValue), value: res.content }))
        console.log(content);
        arr.push(
          new setdata(
            JSON.stringify(content),
            5,
            '累计生产量',
            oldList.find(res => (res.frequencyId * 1 == 5))?.id
          )
        )
      }
      if (_this.leftitemId == '') {
        _this.$message.warning('请选择原物料、强度等级或规范性能等级')
        return
      }
      if (_this.contactId == '') {
        _this.$message.warning('请选择合同')
        return
      }
      if (_this.leftIndex !== 3 && _this.leftId == '') {
        _this.$message.warning('请选择检验类别')
        return
      }
      if (oldList.length == 0 && arr.length == 0) {
        _this.$message.warning('请选择检验频率')
        return
      }
      let allHasData = arr.filter((item) => (
        oldList.some((items) => (item.id == items.id))
      ))
      let deleteData = oldList.filter((item) => (
        !allHasData.some((items) => (item.id == items.id))
      ))
      deleteData.forEach(item => { item.status = 0 })
      console.log([...arr, ...deleteData]);
      saveStationTest([...arr, ...deleteData]).then((res) => {
        if (res.code * 1 === 1001) {
          _this.$message.success("保存成功")
          _this.getStation()
          _this.loading = false
        }
      });
    }
  },
};